package com.jisu.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class JWTUtil {
    private static final   String TOKENKey="79135jkl";

    /**
     * 生成token
     * @param map
     * @return 返回token
     */
    public static String getToken(Map<String,String> map){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,7);//7天过期

        //添加payload
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });

        builder.withExpiresAt(instance.getTime());//设置令牌过期时间
        //生成并返回token
        return builder.sign(Algorithm.HMAC256(TOKENKey)).toString();
    }

    /**
     * 验证token
     *
     * @param token
     * @return
     */
    public static boolean verify(String token){
        try {
            // 添加验证逻辑，验证失败会抛出异常
            JWT.require(Algorithm.HMAC256(TOKENKey)).build().verify(token);
            return true;  // 验证成功返回true
        } catch (Exception e) {
            return false; // 令牌无效或过期
        }
    }

    /**
     * 获取token中payload
     * @param token
     * @return
     */
    public static DecodedJWT getTokenInfo(String token){
        return JWT.require(Algorithm.HMAC256(TOKENKey)).build().verify(token);
    }
}